<template>
    <Card :bordered="true" class="event-report" :id="'report-view'+this.chartconfig[this.indexID].id">
        <Row type="flex" justify="space-between" class="code-row-bg">
        </Row>
        <Row class="chart">
            <Col span="24">
                <Spin v-if="loading" fix>
                    <Icon type="ios-loading" size=24 class="demo-spin-icon-load"></Icon>
                    <div>加载中...</div>
                </Spin>
                <div :id="`myCharts`+chartconfig[indexID].id" class="echarts"></div>
            </Col>
        </Row>
    </Card>
</template>
<script>
    import ElementResize from '../../../../components/ElementResize'
    export default {
        name: "EventReport",
        props: {
            events: Array,
            properties: Array,
            measures: Array,
            chartconfig:Array,
            base:null,
            dashboardId:Array,
            indexID:Number
        },
        data: function() {
            return {
                // flexNum:'6',
                timeUnits: [
                    {
                        label: '无时间分组',
                        value: 'none'
                    },
                    {
                        label: '按天',
                        value: 'day'
                    },
                    {
                        label: '按周',
                        value: 'week'
                    },
                    {
                        label: '按月',
                        value: 'month'
                    }
                ],
                loading: true,
                time: {
                    start: this.$sessionStore.getDay(-7),
                    end: new Date().toLocaleDateString('cn',{year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g,'-'),
                    unit: 'none',
                },
                dateValue: [this.$sessionStore.getDay(-7),this.$sessionStore.getDay(0)],
                indicator: '',
                dimension: [],
                chart: {
                    eventChart: null,
                    options: {
                        title: {
                            text: ''
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        grid: {
                            left: '0%',
                            right: '3%',
                            containLabel: true
                        },
                        legend: {
                            data:[]
                        },
                        toolbox: {
                            feature: {
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: []
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: []
                    },
                },
                table: {
                    columns: [],
                },
                resultSet: [],
            };
        },
        computed: {
            eventMap: function() {
                let eventMap = {};
                for(let i = 0; i < this.events.length; i++) {
                    eventMap[this.events[i].name] = this.events[i];
                }
                return eventMap;
            },
            measureMap: function() {
                let measureMap = {};
                    for(let i = 0; i < this.measures.length; i++) {
                        measureMap[this.measures[i].name] = this.measures[i];
                    }
                return measureMap;
            },
            indicators: function() {
                let indicators = [];
                let obj = {};
                let config = eval('(' +this.chartconfig[this.indexID].config+ ')');
                for(let i = 0; i < config.indicators.length; i++) {
                    for(let j = 0; j < config.indicators[i].measure.length; j++) {
                        let eventName = config.indicators[i].event;
                        let measureName = config.indicators[i].measure[j].name;
                        if(!obj[eventName + "_" + measureName]) {
                            if(eventName in this.eventMap && measureName in this.measureMap) {
                                indicators.push({
                                    label: this.eventMap[eventName].displayName + "的" + this.measureMap[measureName].displayName,
                                    value: eventName + "_" + measureName
                                });
                                obj[eventName + "_" + measureName] = true;
                            }
                        }
                    }
                }
                let str=this.chartconfig[this.indexID].indicators.split(",")
                let newIndicators=[]
                for (let k = 0; k < indicators.length; k++) {
                   for (let o = 0; o < str.length; o++) {
                     if(indicators[k].value==str[o]){
                         newIndicators.push(indicators[k])
                     }
                       
                   }
                }
                return newIndicators
            },
            groups: function() {
                let groups = [];
                let obj = {};
                let config = eval('(' +this.chartconfig[this.indexID].config+ ')');
                for(let i = 0; i < this.resultSet.length; i++) {
                    let label = "";
                    for(let j = 0; j < config.dimensions.length; j++) {
                        if(j === config.dimensions.length - 1){
                            label += this.resultSet[i][config.dimensions[j]];
                        } else {
                            label += this.resultSet[i][config.dimensions[j]]+",";
                        }
                    }
                    if(!obj[label]) {
                        groups.push({
                            label: label,
                            value: label
                        });
                        obj[label] = true;
                    }
                }
                return groups;
            },
           
        },
        methods: {
            showDimensionLabel: function(hiddenTags) {
                return "显示分组";
            },
            showData: function() {
                this.query();
            },
            query: function() {
                let _that = this;
                _that.loading = true;
                let config = eval('(' +_that.chartconfig[_that.indexID].config+ ')');
                    if(_that.chartconfig[_that.indexID].type  == "event"){
                        _that.$axios.post(_that.$api.report + "/analysis/event",
                        {
                            time:{start: "2019-08-24", end: "2019-11-22", unit: "none"},
                            config: config
                        },
                        {
                            headers: {
                                "Authorization": "Bearer "+_that.$sessionStore.fetch(),
                                "Accept": "application/json"
                            },
                            params: {
                                projectId: _that.$store.state.projectId
                            }
                        }).then(response => {
                            if (response.status === 200) {
                                _that.resultSet = response.data;
                                 
                                _that.updateChart();
                            }
                        })
                        .catch(error => {
                            console.log(error);
                        }).finally(() => {
                            _that.loading = false;
                        })
                        } 
                    else if(_that.chartconfig[_that.indexID].type == "ad"){
                     
                        _that.$axios.post(_that.$api.report + "/analysis/ad",
                        {
                            time:{start: "2019-08-24", end: "2019-11-22", unit: "none"},
                            config: config
                        },
                        {
                            headers: {
                                "Authorization": "Bearer "+_that.$sessionStore.fetch(),
                                "Accept": "application/json"
                            },
                            params: {
                                projectId: _that.$store.state.projectId
                            }
                        }).then(response => {
                            if (response.status === 200) {
                                _that.resultSet = response.data;

                                _that.updateChart();
                            }
                        })
                        .catch(error => {
                            console.log(error);
                        }).finally(() => {
                            _that.loading = false;
                        });
                    }
            },
            updateChart: function() {
                let options = {
                    title: {
                        text: ''
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:[]
                    },
                    grid: {
                        left: '0%',
                        right: '3%',
                        bottom:'3%',
                        top:'10%',
                        containLabel: true
                    },
                    toolbox: {
                        feature: {
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: []
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [],
                };
                let obj = {};
                let config = eval('(' +this.chartconfig[this.indexID].config+ ')');
                if(this.time.unit =='none'){
                    for(let index = 0; index < this.indicators.length; index++){
                        options.legend.data.push(this.indicators[index].label);
                        let seriesData = [];
                        for(let i = 0; i < this.resultSet.length; i++) {
                            let label = "";
                            for (let j = 0; j < config.dimensions.length; j++) {
                                if (j === config.dimensions.length - 1) {
                                    label += this.resultSet[i][config.dimensions[j]];
                                } else {
                                    label += this.resultSet[i][config.dimensions[j]] + ",";
                                }
                            }
                            if(!obj[label]){
                                options.xAxis.data.push(label);
                                obj[label] = true;
                            }
                            seriesData.push(this.resultSet[i][this.indicators[index].value]);
                        }
                        options.series.push({
                            name: this.indicators[index].label,
                            type: this.chartconfig[this.indexID].chartType,
                            smooth: true,
                            data: seriesData
                        });
                    }
                }else{
                    for(let index = 0; index < this.dimension.length; index++) {
                        options.legend.data.push(this.dimension[index]);
                        let seriesData = [];
                        for(let i = 0; i < this.resultSet.length; i++) {
                            let label = "";
                            for (let j = 0; j < config.dimensions.length; j++) {
                                if (j === config.dimensions.length - 1) {
                                    label += this.resultSet[i][config.dimensions[j]];
                                } else {
                                    label += this.resultSet[i][config.dimensions[j]] + ",";
                                }
                            }
                            if (this.dimension[index] === label) {
                                if(!obj[this.resultSet[i].date]) {
                                    options.xAxis.data.push(this.resultSet[i].date);
                                    obj[this.resultSet[i].date] = true;
                                }
                                seriesData.push(this.resultSet[i][this.indicator]);
                            }
                        }
                        options.series.push({
                            name: this.dimension[index],
                            type: this.chartconfig[this.indexID].chartType,
                            smooth: true,
                            data: seriesData
                        });
                    }

                }
                this.chart.eventChart.setOption(options, true);
            }
        },
        mounted: function() {
            let $echartsDOM = document.getElementById('myCharts'+this.chartconfig[this.indexID].id)
            let myCharts = this.$echarts.init($echartsDOM,'light');
            this.chart.eventChart = this.$echarts.init(myCharts._zr.dom, 'light');
            this.chart.eventChart.setOption(this.chart.options, true);
            this.query();
            ElementResize.on(document.getElementById('report-view'+this.chartconfig[this.indexID].id), () => {
               this.chart.eventChart.resize();
            });
            if(this.indicators.length > 0) {
                this.indicator = this.indicators[0].value;
                
            }
        },
        watch:{
            indicators:function(){
                if(this.indicators.length > 0) {
                    this.indicator = this.indicators[0].value
                }
            },
            groups:function(){
                if(this.groups.length > 0) {
                    this.dimension.splice(0, this.dimension.length)
                    for(let i = 0; i < Math.min(10,this.groups.length); i++) {
                        this.dimension.push(this.groups[i].value)
                    }
                }
            },
            time:{
                handler(newdate,olddate){
                    this.showData()
                    
                },
                deep:true
            },
            indicator:function() {
                this.updateChart()
            },
            dimension:function() {
                this.updateChart()
            },
            // chartType: function() {
            //     if(this.chartType=='table'){
            //         this.$parent.$parent.$parent.$parent.$parent.chengeChartType(this.indexID,'table')
            //     }else if(this.chartType=='number'){
            //         this.$parent.$parent.$parent.$parent.$parent.chengeChartType(this.indexID,'number')
            //     }else{
            //         this.updateChart();
            //     }
               
            // },
        }
    }
</script>

<style scoped>
    .event-report {
        padding: 0px;
        margin: 0px;
        border: none;
    }
    .filters {
        margin-bottom: 10px;
    }
    .table-actions {
        margin-bottom: 10px;
    }
    .echarts {
        width: 100%;
        height: 255px;
    }
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .demo-spin-col{
        height: 100px;
        position: relative;
    }
</style>